/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.meta.service;

import cn.hutool.core.io.IoUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.base.Strings;
import com.je.common.base.DynaBean;
import com.je.common.base.exception.PlatformException;
import com.je.common.base.exception.PlatformExceptionEnum;
import com.je.common.base.mapper.query.NativeQuery;
import com.je.common.base.service.MetaResourceService;
import com.je.common.base.util.ArrayUtils;
import com.je.meta.rpc.excel.AbstractExcelRpcExportService;
import com.je.meta.service.excel.ExportExcelColumnWidthStyleStrategy;
import com.je.meta.service.excel.ExportExcelVerticalCellStyleStrategy;
import com.je.meta.service.excel.ExportExcelWriteStyleHandler;
import com.je.meta.service.excel.converter.ExcelExportConverterFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.*;

@Service("excelRpcGridExportService")
public class ExcelRpcGridExportServiceImpl extends AbstractExcelRpcExportService {

    private static final String COLUMNS = "RESOURCECOLUMN_MORECOLUMNNAME,RESOURCECOLUMN_WIDTH,RESOURCECOLUMN_CODE," +
            "RESOURCECOLUMN_XTYPE,RESOURCECOLUMN_NAME,RESOURCEFIELD_XTYPE,RESOURCEFIELD_CONFIGINFO";

    @Autowired
    private MetaResourceService metaResourceService;

    @Override
    public InputStream export(JSONObject params, HttpServletRequest request) {
        String funcId = params.getString("funcId");
        //获取数据
        List<DynaBean> datas = getDate(params, request);
        //字段配置信息
        List<DynaBean> columns = metaResourceService.selectByTableCodeAndNativeQueryWithColumns("je_core_vcolumnandfield", NativeQuery.build().apply(" AND ( RESOURCEFIELD_XTYPE NOT IN ( 'ckeditor' ) OR RESOURCEFIELD_XTYPE IS NULL) " +
                "AND RESOURCECOLUMN_FUNCINFO_ID='" + funcId + "' AND RESOURCECOLUMN_HIDDEN='0' AND RESOURCECOLUMN_XTYPE NOT IN ('actioncolumn') ORDER BY SY_ORDERINDEX"), "RESOURCECOLUMN_MORECOLUMNNAME,RESOURCECOLUMN_WIDTH,RESOURCECOLUMN_CODE,RESOURCECOLUMN_XTYPE,RESOURCECOLUMN_NAME,RESOURCEFIELD_XTYPE,RESOURCEFIELD_CONFIGINFO");
        //加入多方案后会查出重复字段，需去重，去重规则:若相同字段的类型不同，首选rgroup, cgroup, cbbfield，若相同，取第一个
        delRepeat(columns);
        //封装字典数据
        Map<String, Map<String, String>> ddInfos = excelRpcService.buildDicDatas(columns);
        //获取tile
        List<List<String>> headList = excelRpcService.getReportTile(funcId, params.getString("title"));
        //格式化数据
        List<List<Object>> list = buildExportData(funcId, datas, ddInfos, columns);
        //初始化输出流
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        EasyExcel.write(outputStream).head(headList)
                .registerWriteHandler(new ExportExcelColumnWidthStyleStrategy())
                .registerWriteHandler(new ExportExcelVerticalCellStyleStrategy())
                .registerWriteHandler(new ExportExcelWriteStyleHandler())
                .sheet("sheet1").doWrite(list);
        //输出转输入
        ByteArrayInputStream inputStream = IoUtil.toStream(outputStream.toByteArray());
        IoUtil.close(outputStream);
        return inputStream;
    }


    public List<List<Object>> buildExportData(String funcId, List<DynaBean> datas, Map<String, Map<String, String>> ddInfos, List<DynaBean> formColumns) {
        List<DynaBean> funcGridFileds = metaResourceService.selectByTableCodeAndNativeQueryWithColumns("JE_CORE_RESOURCECOLUMN", NativeQuery.build()
                .eq("RESOURCECOLUMN_FUNCINFO_ID", funcId).in("RESOURCECOLUMN_XTYPE", "rownumberer", "uxcolumn")
                .eq("RESOURCECOLUMN_HIDDEN", "0").orderByAsc("SY_ORDERINDEX"), COLUMNS);
        List<List<Object>> list = new ArrayList<>();
        int i = 1;
        for (DynaBean dynaBean : datas) {
            List<Object> dataMap = new ArrayList<>();
            HashMap<String, Object> map = dynaBean.getValues();
            for (DynaBean gridFiled : funcGridFileds) {
                String filedCode = gridFiled.getStr("RESOURCECOLUMN_CODE");
                String type = gridFiled.getStr("RESOURCECOLUMN_XTYPE");
                if (type.equals("rownumberer")) {
                    dataMap.add(i);
                    i++;
                    continue;
                }
                DynaBean formColumn = null;
                for (DynaBean fc : formColumns) {
                    if (fc.getStr("RESOURCECOLUMN_CODE").equals(filedCode)) {
                        formColumn = fc;
                    }
                }
                if (formColumn == null) {
                    throw new PlatformException(String.format("获取%s导出字段配置信息出错！", filedCode), PlatformExceptionEnum.UNKOWN_ERROR);
                }
                Object value = buildValue(map.get(filedCode), formColumn, ddInfos);
                dataMap.add(value);
            }
            list.add(dataMap);
        }
        return list;
    }

    private Object buildValue(Object value, DynaBean formColumn, Map<String, Map<String, String>> ddInfos) {
        if (Objects.isNull(value)) {
            return "";
        }
        String stringValue = String.valueOf(value);
        if (Strings.isNullOrEmpty(stringValue)) {
            return "";
        }
        String type = formColumn.getStr("RESOURCEFIELD_XTYPE");
        return ExcelExportConverterFactory.getConverter(type).converter(stringValue, formColumn, ddInfos);
    }


    private void delRepeat(List<DynaBean> columns) {
        List<Integer> indexs = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        for (int i = 0; i < columns.size(); i++) {
            DynaBean dynaBean = columns.get(i);
            String code = dynaBean.getStr("RESOURCECOLUMN_CODE");
            String type = dynaBean.getStr("RESOURCEFIELD_XTYPE");
            if (map.containsKey(code)) {
                if ("1".equals(map.get("code"))) {
                    indexs.add(i);
                    continue;
                } else {
                    if (ArrayUtils.contains(new String[]{"rgroup", "cgroup", "cbbfield"}, type)) {
                        String flag = map.get("code").toString();
                        indexs.add(Integer.parseInt(flag.split("_")[1]));
                        map.put(code, "1");
                        continue;
                    } else {
                        indexs.add(i);
                        continue;
                    }
                }
            }
            if (ArrayUtils.contains(new String[]{"rgroup", "cgroup", "cbbfield"}, type)) {
                map.put(code, "1");
            } else {
                map.put(code, "2" + "_" + i);
            }
        }
        for (Integer integer : indexs) {
            columns.remove(integer);
        }
    }
}
